<?php

namespace App\Api\Controllers\v1;

use App\Http\Controllers\ApiController;
use App\Http\Library\WeChat\MiniWeChat;
use App\Http\Requests\UserRegister;
use App\Http\Response\ApiResponse;
use App\Models\User;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Throwable;
use hg\apidoc\annotation as Apidoc;

/**
 * 授权接口
 * @Apidoc\Group("oauth")
 * @Apidoc\Sort(2)
 */
class OauthController extends ApiController
{

    /**
     * 微信静默登录
     * @Apidoc\Url("/api/v1/oauth/wechatLogin")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("code", type="string",require=true, desc="code")
     * @Apidoc\Returned("token", type="string", desc="token")
     * @Apidoc\Returned("session_key", type="string", desc="session_key")
     * @Apidoc\Returned(ref="userInfo")
     */
    public function wechatLogin(Request $request): ApiResponse
    {
        $params = $this->request->only(['code','tid']);
        if ($params&&$params['code']){
            try {
                return $this->auth->weChatLogin($params,$request);
            }catch (\Exception $e){
                return $this->response()->error($e->getMessage());
            }
        }
        return $this->response()->error("code参数不能为空!");
    }

    /**
     * 更新用户资料
     * @Apidoc\Url("/api/v1/oauth/saveInfo")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("nickname", type="string",require=true, desc="昵称")
     * @Apidoc\Param("avatar", type="string",require=true, desc="头像")
     * @Apidoc\Param("mobile", type="string",require=true, desc="电话")
     * @Apidoc\Returned(ref="userInfo")
     */
    public function saveInfo(UserRegister $request): ApiResponse
    {
        $params = $request->validated();
        DB::beginTransaction();
        try {
            $user = User::query()->where("id",$this->user_id)->first();
            $user->nickname = $params['nickname'];
            $user->avatar = $params['avatar'];
            $user->mobile = $params['mobile'];
            $res = $user->save();
            DB::commit();
        }catch (Throwable|Exception $e){
            DB::rollBack();
            return $this->response()->error($e->getMessage());
        }
        if ($res){
            return $this->response()->success("提交成功!")->data(['userInfo'=>$this->getUserInfo()]);
        }else{
            return $this->response()->error("提交失败!");
        }
    }

    /**
     * 授权解密手机号
     * @Apidoc\Url("/api/v1/oauth/mobile")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("code", type="string",require=true, desc="手机号解密的code")
     * @Apidoc\Returned("mobile", type="string", desc="手机号信息")
     */
    public function mobile(): ApiResponse
    {
        $code = $this->request->input("code");
        if (!$code){
            return $this->response()->error("code获取失败");
        }
        $wechat = MiniWeChat::instance();
        try {
            $result = $wechat->getUserPhoneNumber($code);
            if ($result['errcode']){
                throw new Exception($result['errmsg']);
            }else{
                if ($result['errcode']==-1){
                    throw new Exception("系统繁忙，此时请开发者稍候再试!");
                }
                $phone_info = $result['phone_info'];
                $mobile = $phone_info['phoneNumber'];
                $res = User::query()->where("id",$this->user_id)->update(['mobile'=>$mobile]);
            }
        }catch (Exception $e){
            $message = $e->getMessage();
            return $this->response()->error($message);
        }
        if ($res){
            return $this->response()->success("ok!")->data(['mobile'=>$mobile]);
        }else{
            return $this->response()->error("解密手机号失败");
        }
    }

}
